package com.tarena.lbs.business.controller;

import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.param.UserLocationParam;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Tag(name = "店铺相关功能接口")
@RestController
@Slf4j
public class StoreController {
    @Autowired
    private StoreService storeService;
    @DubboReference
    private UserApi userApi;


    @Operation(summary = "查询店铺列表")
    @PostMapping("/admin/basic/store/getAll")
    public Result<PageResult<StoreVO>> pageList(@RequestBody StoreQuery query)
        throws BusinessException {
//        PageResult pageResult = new PageResult();
//        pageResult.setObjects(new ArrayList<>());
//        pageResult.setTotal(1L);
//        pageResult.setPageSize(1);
        log.debug("Controller层接收到的参数: {}", query);
        Integer businessId = getLoginId();
        if(businessId!=null && businessId>0){
            query.setBusinessId(businessId);
        }

        PageResult<StoreVO> pageResult = storeService.pageList(query);
        return new Result(pageResult);
    }

    /**
     * 新增店铺
     * @param param
     * @return
     * @throws BusinessException
     */
    @Operation(summary = "新增店铺")
    @PostMapping("/admin/basic/store/add")
    public Result<Void> save(@RequestBody StoreParam param)
        throws BusinessException {
        // 添加日志记录，确认前端传入的参数
        log.debug("Controller层接收到的参数: {}", param);
        storeService.addStore(param);
        return Result.success();
    }

    @Operation(summary = "编辑店铺")
    @PostMapping("/admin/basic/store/update")
    public Result<Void> update(@RequestBody StoreParam param)
        throws BusinessException {
        storeService.updateStore(param);
        return Result.success();
    }

    @Operation(summary = "删除店铺")
    @DeleteMapping("/admin/basic/store/delete/{id}")
    public Result<Void> delete(@PathVariable Long id)
        throws BusinessException {
        storeService.deleteStore(id);
        return Result.success();
    }
    @Operation(summary = "查询店铺详情")
    @GetMapping("/admin/basic/store/{id}")
    public Result<StoreVO> storeEdit(@PathVariable Integer id)
        throws BusinessException {
        StoreVO storeVO = storeService.storeEdit(id);
        return new Result<>(storeVO);
    }
    //查询店铺的活动
    @Operation(summary = "查询店铺活动")
    @GetMapping("/admin/basic/store/getActivity/{id}")
    public Result<List<ActivityVO>> getActivity(@PathVariable Integer id)
        throws BusinessException {
        List<ActivityVO> list = storeService.getActivity(id);
        return new Result<>(list);
    }

    //查询 属于当前登录用户 所属商家 和满足区域条件的店铺列表
    @Operation(summary = "查询区域下的店铺列表")
    @PostMapping("/admin/basic/store/getStoreByCity")
    public Result<PageResult<StoreVO>> getStoreByCity(@RequestBody AreaStoreQuery query)
            throws BusinessException {
        List<StoreVO> list = storeService.getStoreByCity(query);
        PageResult<StoreVO> pageResult = new PageResult<>();

        PageInfo<StoreVO> pageInfo =new PageInfo<>(list);
        pageResult.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        pageResult.setPageSize(query.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setObjects(list);
        return new Result<>(pageResult);
    }
    //手机小程序定位上报
    @Operation(summary = "手机小程序定位上报")
    @PostMapping("/basic/store/location")
    public Result<Void> location(@RequestBody UserLocationParam param)
            throws BusinessException {
        storeService.saveUserLocation(param);

        return Result.success();
    }

    @Operation(summary = "查询店铺及其文章")
    @GetMapping("/admin/basic/store/getStoreAndArticle")
    public Result<Map<String,Integer>> getStoreAndArticle()
        throws BusinessException {
        return storeService.getStoreAndArticle();
    }


    /**
     * 获取当前登录商家的信息
     * @return
     * @throws BusinessException
     */
    private Integer getLoginId() throws BusinessException {
        // 1. 获取当前用户认证信息
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        // 2. 检查用户是否已认证
        Asserts.isTrue(userPrinciple == null, new BusinessException("-2", "用户认证解析失败"));
        AdminDto adminDto = new AdminDto();
        // 3. 权限细化：商家只能查询自己的店铺
        if(userPrinciple.getRole() == Roles.SHOP){
            //假设商家ID存储在UserPrinciple的扩展字段中
            adminDto = userApi.getAdminById(userPrinciple.getId());
            // 判断商家信息是否为空
            Asserts.isTrue(adminDto == null, new BusinessException("500", "商家信息不存在"));
            //query.setBusinessId(adminDto.getBusinessId()); // 向查询参数中注入商家ID，限制数据范围
        }
        return adminDto.getBusinessId();
    }

}